<template>
  <div>
    <el-tabs v-model="currentTab" type="card" class="center-tabs">
      <el-tab-pane label="顾客详情" name="customerDetails" />
      <el-tab-pane label="方案管理" name="projectManagement" />
    </el-tabs>
    <div v-show="currentTab === 'customerDetails'">
      <CustomerDetails
        :basicInfo="baseInfo"
        v-if="currentTab === 'customerDetails'"
      ></CustomerDetails>
    </div>
    <div v-show="currentTab === 'projectManagement'">
      <div class="tips1" v-if="baseInfo.referenceStatus">
        咨询方案 咨询医生：{{ baseInfo.consultationer }} 咨询日期：{{
          baseInfo.consultationTime
        }}
      </div>
      <div v-else-if="baseInfo.updateStatus" class="tips">
        医生方案 医生：{{ baseInfo.doctor }} 诊断日期：{{ baseInfo.doctorTime }}
      </div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="68px"
        class="formBox"
      >
        <el-form-item label="顾客编号" prop="visitNum">
          <el-input
            v-model="queryParams.visitNum"
            placeholder="请输入顾客编号"
            :disabled="true"
            clearable
            style="width: 160px"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="patientName" label-width="48px">
          <el-input
            v-model="queryParams.patientName"
            placeholder="请输入顾客姓名"
            :disabled="true"
            clearable
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex" label-width="48px">
          <el-select
            v-model="queryParams.sex"
            placeholder="下拉选择"
            :disabled="true"
            clearable
            style="width: 60px"
          >
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="48px">
          <el-select
            v-model="queryParams.status"
            placeholder="待咨询"
            :disabled="true"
            clearable
            style="width: 140px"
          >
            <el-option
              v-for="dict in dict.type.sys_diagnosis_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="就诊门诊" prop="patientName">
          <el-input v-model="queryParams.deptName" placeholder="请输入就诊科室" :disabled="true" clearable
                    style="width: 160px" />
        </el-form-item>
        <el-form-item label-width="0px">
          <el-badge :value="Listtotal" class="totalItem">
            <el-button type="primary" size="mini" @click="handleAdd"
              >检测指标</el-button
            >
          </el-badge>
          <el-badge :value="warmReminderRecordParamsTotal" class="totalItem">
            <el-button type="primary" size="mini" @click="warmReminder"
              >温馨提示</el-button
            >
          </el-badge>

          <el-button
            type="success"
            size="mini"
            @click="saveAllPlan"
            v-if="baseInfo.referenceStatus"
            :disabled="Number(queryParams.status) >= 3"
            >审核通过</el-button
          >
          <el-button
            type="success"
            size="mini"
            @click="updateAllPlan"
            v-else-if="baseInfo.updateStatus"
            :disabled="Number(queryParams.status) == 4"
            >修改方案</el-button
          >
          <el-button type="success" size="mini" @click="saveAllPlan" v-else
            >保存方案</el-button
          >
        </el-form-item>
        <el-form-item label="诊断医生">
          <el-select
            v-model="queryParams.doctor"
            filterable
            clearable
            placeholder="治疗医生"
            style="width: 160px"
          >
            <el-option
              v-for="(item, index) in doctorList"
              :key="index"
              :label="item.nickName"
              :value="item.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="formBox">
        <!-- v-if="baseInfo.updateStatus" -->

        <span>本次就诊是:</span>
        <el-radio-group
          v-model="diagnosisRadio"
          style="margin-left: 10px"
          @input="changeDiagnosisRadio"
        >
          <el-radio :label="0">初诊</el-radio>
          <el-radio :label="1">复诊</el-radio>
        </el-radio-group>
        <el-button
          type="success"
          size="mini"
          @click="showBaseInfoData"
          style="margin-left: 20px"
          >历史诊断记录
          <span style="color: red"
            >({{ baseInfoData.length - 1 }} 次）
          </span></el-button
        >

        <span
          v-if="latestAppointmentItem && latestAppointmentItem.appointmentDate"
          style="
            margin-left: 20px;
            margin-right: 20px;
            font-weight: bold;
            color: red;
          "
          >下次预约日期:{{ latestAppointmentItem.appointmentDate }}
          {{ latestAppointmentItem.week }}
          {{ latestAppointmentItem.timeSlot == 0 ? "上午" : "下午" }}</span
        >
        <!-- <el-button type="primary" size="mini" style="margin-left: 10px" @click="openDiagnosisReview">复诊提醒</el-button> -->

        <el-button type="success" size="mini" @click="addNext"
          >下次预约</el-button
        >

        <el-button
          type="primary"
          size="mini"
          style="margin-left: 10px"
          @click="openInviteQrcode"
          >邀请二维码</el-button
        >
      </div>
      <el-form
        :model="projectForm"
        ref="projectForm"
        size="small"
        label-width="68px"
        :rules="projectFormRules"
        label-position="left"
      >
        <div class="formBox">
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
              <div>
                <el-form-item label="添加诊断" prop="diseaseClassifyName">
                  <el-select
                    v-model="projectForm.diseaseClassifyName"
                    filterable
                    placeholder="下拉选择之后点击加入"
                    clearable
                    style="width: 330px"
                    @change="getFxAndFq"
                  >
                    <el-option
                      v-for="item in classifyList"
                      :key="item.diseaseClassifyId"
                      :label="item.diseaseClassifyName"
                      :value="item.diseaseClassifyName"
                    />
                  </el-select>
                  <!-- <el-button size="mini" type="primary" @click="updateDiagnosis" v-if="btnUpdateStatus">修改</el-button> -->
                  <el-button
                    size="mini"
                    type="primary"
                    @click="addDiagnosis"
                    style="margin-left: 15px"
                    :disabled="Number(queryParams.status) == 4"
                    >加入</el-button
                  >
                  <!-- <el-button size="mini" @click="saveDiagnosis">保存诊断</el-button> -->
                </el-form-item>
              </div>
              <div v-show="Fx.length > 0" class="mt5">
                <el-form-item label="分型" prop="fxValue">
                  <!--                  <el-radio-group v-model="projectForm.fxValue">-->
                  <!--                    <el-radio v-for="item in Fx" :key="item" :label="item" :value="item"></el-radio>-->
                  <!--                  </el-radio-group>-->
                  <el-checkbox-group v-model="projectForm.fxValue">
                    <el-checkbox
                      v-for="(item, index) in Fx"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
              <div v-show="Fq.length > 0" class="mt5">
                <el-form-item label="分期" prop="fqValue">
                  <el-radio-group v-model="projectForm.fqValue">
                    <el-radio
                      v-for="item in Fq"
                      :key="item"
                      :label="item"
                      :value="item"
                    ></el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div class="mt5 mt15">
                <el-collapse v-model="activeName" accordion>
                  <el-form-item label="部位" prop="partId" clearable>
                    <el-select
                      v-model="projectForm.partId"
                      multiple
                      clearable
                      filterable
                      @focus="openCollapse"
                      placeholder="请选择部位"
                      style="width: 400px"
                    >
                      <el-option
                        v-for="(dict,index) in dict.type.sys_face_part"
                        :key="index"
                        :label="dict.label"
                        :value="dict.label"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="" prop="partId">
                    <el-collapse-item name="1">
                      <el-checkbox-group v-model="projectForm.partId">
                        <el-checkbox
                          v-for="(dict,index)  in dict.type.sys_face_part"
                          :key="index"
                          :label="dict.label"
                          :value="dict.label"
                          style="width: 100px"
                        ></el-checkbox>
                      </el-checkbox-group>
                    </el-collapse-item>
                  </el-form-item>
                </el-collapse>
              </div>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
              <div v-for="item in diagnosisList" :key="item.id" class="mt5">
                <el-form-item label="诊断">
                  <el-input
                    v-model="item.diagnosis"
                    placeholder="请输入诊断"
                    disabled
                    clearable
                    style="width: 480px; margin-bottom: 15px"
                  />
                  <!-- <el-button size="mini" @click="updateItemDiagnosis(item)">修改</el-button> -->
                  <el-button
                    size="mini"
                    @click="delDiagnosis(item)"
                    style="margin-left: 15px"
                    :disabled="Number(queryParams.status) == 4"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
              <div>
                <el-form-item label="主诉" prop="doctorNote">
                  <el-input
                    v-model="projectForm.doctorNote"
                    placeholder="请输入主诉"
                    clearable
                    style="width: 550px; margin-bottom: 15px"
                  />
                </el-form-item>
              </div>
              <div>
                <el-form-item label="现病史" prop="diagnosisMedical">
                  <el-input
                    v-model="projectForm.diagnosisMedical"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入现病史"
                    clearable
                    style="width: 550px; margin-bottom: 15px"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-form size="small" :inline="true" label-width="68px">
        <div class="formBox">
          <div class="formBox">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                <div>
                  <el-form-item label="添加套餐" prop="mealId">
                    <el-select
                      v-model="projectForm.mealId"
                      filterable
                      placeholder="下拉选择之后点击加入"
                      clearable
                      style="width: 330px"
                    >
                      <el-option
                        v-for="item in mealList"
                        :key="item.setMealId"
                        :label="item.setMealName"
                        :value="item.setMealId"
                      />
                    </el-select>
                    <el-button
                      size="mini"
                      @click="addPackage"
                      type="primary"
                      style="margin-left: 15px"
                      :disabled="Number(queryParams.status) == 4"
                      >加入</el-button
                    >
                  </el-form-item>
                </div>
                <div style="margin-top: 8px">
                  <el-form-item
                    label="添加单项"
                    prop="planCategoryId"
                    clearable
                  >
                    <el-select
                      v-model="projectForm.planCategoryId"
                      filterable
                      @change="changeList"
                      placeholder="请选择方案大类"
                      clearable
                      style="width: 160px"
                    >
                      <el-option
                        v-for="dict in dict.type.sys_plan_category"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="" prop="planId">
                    <el-select
                      v-model="projectForm.planId"
                      filterable
                      placeholder="请选择专病名称"
                      clearable
                      style="width: 160px"
                    >
                      <el-option
                        v-for="(item, index) in singlePlanList"
                        :key="index"
                        :label="item.medicalEquipment"
                        :value="item.planId"
                      ></el-option>
                    </el-select>
                    <el-button
                      size="mini"
                      @click="addSingle"
                      type="primary"
                      style="margin-left: 15px"
                      :disabled="Number(queryParams.status) == 4"
                      >加入</el-button
                    >
                  </el-form-item>
                </div>
              </el-col>
              <!--                        <el-col :span="3" class="price"> 治疗费/总金额 <br />{{ treatmentExpenses }}/{{ totalExpenses}}</el-col>-->
              <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="price" style="margin-top:8px;">
                <div>治疗费:{{ treatmentExpenses }}</div>
                <div>总金额:{{ totalExpenses }}</div>
              </el-col>
            </el-row>
          </div>
          <div class="formBox">
            <el-table :data="sysSetMealPlanListCopy" border>
              <el-table-column
                fixed="left"
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="100"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="deletePlanItem(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="类别"
                align="center"
                prop="category"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span>{{
                    scope.row.category === "1"
                      ? "套餐"
                      : scope.row.category === "2"
                      ? "单项"
                      : ""
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="套餐名称"
                align="center"
                prop="packageName"
                :show-overflow-tooltip="true"
                width="200"
              />
              <el-table-column
                label="项目类别"
                align="center"
                prop="planCategoryId"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span>{{
                    matchDict("sys_plan_category", scope.row.planCategoryId)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="方案名称"
                align="left"
                prop="packageContent"
                :show-overflow-tooltip="true"
                width="260"
              />
              <el-table-column
                label="医嘱参数值"
                align="center"
                prop="parameters"
                :show-overflow-tooltip="true"
                width="150"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    placement="right"
                    effect="light"
                    v-if="
                      scope.row.planCategoryId == 2 && scope.row.parametersList
                        ? scope.row.parametersList.length > 0
                        : false
                    "
                    :disabled="isShowStatus"
                  >
                    <div slot="content">
                      <div
                        style="display: flex; margin-bottom: 15px"
                        v-for="item in scope.row.parametersList"
                        :key="item.label"
                      >
                        <el-input
                          v-model="item.label"
                          placeholder="请输入医嘱名称"
                          style="margin-right: 15px"
                        ></el-input>
                        <el-input
                          v-model="item.value"
                          placeholder="请输入医嘱参数值"
                          style="margin-right: 15px"
                        ></el-input>
                        <el-button
                          size="mini"
                          type="primary"
                          @click="delOptions(item, scope.$index)"
                          >删除</el-button
                        >
                      </div>
                      <el-button
                        size="mini"
                        type="primary"
                        style="display: block; margin: 15px auto"
                        @click="submitOptions(scope.$index)"
                        >提交</el-button
                      >
                    </div>
                    <el-input
                      v-model="scope.row.parameters"
                      placeholder="请输入医嘱参数值"
                    ></el-input>
                  </el-tooltip>
                  <el-input
                    v-else
                    v-model="scope.row.parameters"
                    placeholder="请输入医嘱参数值"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="用法"
                align="center"
                prop="treatmentModalities"
                :show-overflow-tooltip="true"
                width="130"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.treatmentModalities"
                    filterable
                    clearable
                    placeholder="请选择用法"
                  >
                    <el-option
                      v-for="dict in treatmentMethodsList"
                      :key="dict.label"
                      :label="dict.label"
                      :value="dict.label"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="结算价"
                align="center"
                prop="discountPrice"
                :show-overflow-tooltip="true"
                width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.discountPrice"
                    placeholder="请输入结算价"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="用量"
                align="center"
                prop="dosage"
                :show-overflow-tooltip="true"
                width="100"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.dosage"
                    placeholder="请输入用量"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="单位"
                align="center"
                prop="numUnit"
                :show-overflow-tooltip="true"
                width="100"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.numUnit"
                    filterable
                    placeholder="请选择用量单位"
                  >
                    <el-option
                      v-for="dict in numUnitList"
                      :key="dict.label"
                      :label="dict.label"
                      :value="dict.label"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="频次"
                align="center"
                prop="frequency"
                :show-overflow-tooltip="true"
                width="130"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.frequency"
                    placeholder="请选择频次"
                    filterable
                    allow-create
                  >
                    <!-- <el-option v-for="dict in dict.type.sys_dosage_frequency" :key="dict.label"
                        :label="dict.label" :value="dict.label"></el-option> -->
                    <el-option
                      v-for="dict in frequencyList"
                      :key="dict.label"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="数量"
                align="center"
                prop="num"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.num"
                    placeholder="请输入数量"
                    type="number"
                    @input="numInput(scope.row)"
                    @keydown.native="onlyWriteNum"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="点位数"
                align="center"
                prop="pointsNum"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.pointsNum"
                    placeholder="点位数"
                    type="number"
                    @input="pointsNumInput(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="单价"
                align="center"
                prop="price"
                :show-overflow-tooltip="true"
                width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.price"
                    placeholder="请输入单价"
                    type="number"
                    @input="priceInput(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="总价"
                align="center"
                prop="totalPrice"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  {{ scope.row.num * scope.row.pointsNum * scope.row.price }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="优惠率" align="center" prop="discount" width="80" :step="0.01" :min="0" :max="1">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.discount" size="mini" type="number"></el-input>
                </template>
              </el-table-column> -->

              <el-table-column
                label="先敷药"
                align="center"
                prop="isApplication"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span>{{
                    scope.row.isApplication == 0
                      ? "是"
                      : scope.row.isApplication == 1
                      ? "否"
                      : ""
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="治疗仪器"
                align="center"
                prop="instruments"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="领取地点"
                align="center"
                prop="pickingLocation"
                width="202"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.pickingLocation"
                    filterable
                    clearable
                    placeholder="领取地点"
                    style="width: 180px"
                  >
                    <el-option
                      v-for="dict in dict.type.sys_picking_location"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                align="center"
                prop="remark"
                :show-overflow-tooltip="true"
                width="200"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入备注"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="创建时间"
                align="center"
                prop="createTime"
                width="160"
              >
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <!-- 新增检测指标 -->
      <el-dialog
        :title="planTitle"
        :visible.sync="centerDialogVisible"
        v-dialogDrag
        width="90%"
        append-to-body
        :close-on-click-modal="false"
      >
        <detectionAdd
          v-if="centerDialogVisible"
          :baseAdd="baseAdd"
          @closeCenterDialogVisible="closeCenterDialogVisible"
          @refresh="closeCenterDialogVisible"
        >
        </detectionAdd>
      </el-dialog>
      <!-- 复诊提醒日期 -->
      <el-dialog
        title="复诊提醒"
        :visible.sync="diagnosisRadioVisible"
        v-dialogDrag
        width="70%"
        append-to-body
        :before-close="beforeCloseDiagnosisReview"
        :close-on-click-modal="false"
      >
        <el-form :model="diagnosisRadioForm">
          <el-form-item label="选择下次复诊日期" label-width="140px">
            <el-date-picker
              v-model="diagnosisRadioForm.reviewTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="submitDiagnosisRadioForm"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
        <div class="formBox">
          <el-table border v-loading="loading" :data="diagnosisRadioData">
            <el-table-column
              label="序号"
              align="center"
              type="index"
              width="50"
            >
              <template slot-scope="scope">
                <span>{{ getIndex(scope.$index) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="reviewTime"
              label="提醒复诊日期"
              width="180"
            ></el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="nickName"
              label="提醒医生"
            ></el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="createTime"
              label="提醒日期"
              width="180"
            ></el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="reviewStatus"
              label="是否已复诊"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.reviewStatus == "0" ? "否" : "是" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="updateTime"
              label="复诊日期"
              width="180"
            ></el-table-column>
            <el-table-column
              sortable
              align="center"
              prop="receptionDoctorName"
              label="诊断医生"
            ></el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              class-name="small-padding fixed-width"
              width="100"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteReviewItem(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="diagnosisRadioQueryParams.pageNum"
            :limit.sync="diagnosisRadioQueryParams.pageSize"
            @pagination="getReviewList"
          />
        </div>
      </el-dialog>
      <!-- 温馨提示 -->
      <el-dialog
        title="温馨提示"
        :visible.sync="warmReminderVisible"
        v-dialogDrag
        width="90%"
        append-to-body
        :close-on-click-modal="false"
        :before-close="closeWarmReminderVisible"
      >
        <warmReminder
          v-if="warmReminderVisible"
          :baseInfo="baseInfo"
          @closeWarmReminderVisible="closeWarmReminderVisible"
        ></warmReminder>
      </el-dialog>
      <!-- 历史记录 -->
      <el-dialog
        title="历史诊断记录"
        :visible.sync="historyVisible"
        v-dialogDrag
        width="90%"
        append-to-body
        :close-on-click-modal="false"
      >
        <diagnosisCitate
          v-if="historyVisible"
          :basicInfo="baseInfo"
          @comfirmCitate="addPlan"
        ></diagnosisCitate>
      </el-dialog>
      <!-- 邀请二维码 -->
      <el-dialog
        title="邀请二维码"
        :visible.sync="qrCodeOpen"
        @close="closeQrCodeDialog"
        width="600px"
        append-to-body
      >
        <div class="qrcode-box">
          <!-- <div class="qrcode">
            <div v-if="qrCodeOpen" class="qrcode" ref="qrCodeDiv"></div>
            <div style="text-align: center">ipad</div>
          </div> -->
          <div class="qrcode">
            <div v-if="qrCodeOpen" class="qrcode" ref="qrCodeDiv1"></div>
            <div style="text-align: center">请用平板或者手机扫描二维码</div>
          </div>
        </div>
      </el-dialog>
      <!-- 下次预约 -->
      <el-dialog
        title="预约"
        :visible.sync="appointReservaDialogVisible"
        v-dialogDrag
        width="80%"
        append-to-body
        :close-on-click-modal="false"
        @close="closeAppointReserva"
      >
        <appointReservate
          v-if="appointReservaDialogVisible"
          :basicInfo="baseInfo"
        >
        </appointReservate>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import { latestAppointment } from "@/api/appointManage/appointReserve";
import { listClassify } from "@/api/system/classify";
import {listPlan, listMeal, getMeal, listMealDept, listPlanDept} from "@/api/system/plan";
import {
  addDoctorPlan,
  doctorEdit,
  getDoctorReference,
  updateDoctorPlan,
  getList,
} from "@/api/doctorWorkstation/diagnosisList";
import appointReservate from "@/views/components/customerDetail/appointReservate";
import detectionAdd from "@/views/components/detection/add";
import warmReminder from "@/views/components/warmReminder/warmReminder";
import diagnosisCitate from "@/views/components/customerDetail/diagnosisCitate";
import CustomerDetails from "@/views/components/customerDetail/customerDetail";
import {
  addReview,
  deleteReview,
  getReview,
  uploadReview,
} from "@/api/patientReview/review";
import { listText } from "@/api/system/text";
import {
  addTips,
  deleteTips,
  getTips,
  getTipsList,
  updateTips,
} from "@/api/warmReminder/warmReminder";
import { getListUser } from "@/api/system/user";
import { listDetectionVisit } from "@/api/photoWorkstation/detection";

export default {
  name: "Detail",
  dicts: [
    "sys_diagnosis_status",
    "sys_patient_properties",
    "sys_skin_tone",
    "sys_patient_sort",
    "sys_user_sex",
    "sys_manage_diseases",
    "sys_face_part",
    "sys_normal_disable",
    "sys_plan_category",
    "sys_dosage_unit",
    "sys_treatment_instrument",
    "sys_treatment_parameter",
    "sys_dosage_frequency",
    "sys_plan_usage",
    "sys_yes_no",
    "sys_picking_location",
  ],
  props: ["baseInfo"],
  // props: {
  //   baseInfo:{
  //     type: Object,
  //     default:{}
  //   },
  //   currentTab:{
  //     type: String,
  //     default:'projectManagement'
  //   }
  // },
  components: {
    CustomerDetails,
    detectionAdd,
    warmReminder,
    diagnosisCitate,
    appointReservate,
  },
  data() {
    return {
      qrCodeOpen: false, // 邀请码
      urlText: "", // 邀请码url
      urlText1: "", // 邀请码url
      loading: false, // 遮罩层
      total: 0, // 总条数
      currentTab: "projectManagement",
      classifyList: [],
      Fx: [],
      Fq: [],
      diagnosisList: [],
      btnUpdateStatus: false,
      currentDiagnosis: null,
      singlePlanList: [],
      mealList: [],
      sysSetMealPlanList: [],
      // 查询参数
      queryParams: {
        visitNum: undefined, //顾客编号
        patientName: undefined, //顾客姓名
        sex: undefined, //顾客性别
        status: undefined, //状态
        doctor: "",
        deptName:'',
      },
      baseInfoData: [],
      centerDialogVisible: false,
      baseAdd: { isDetail: false },
      planTitle: "",
      // projectForm: { diseaseClassifyName: '', fxValue: '', fqValue: '', partId: [], mealId: '', planId: '', planCategoryId: '', diagnosisMedical: '', doctorNote: '' },
      projectForm: {
        diseaseId: "",
        diseaseClassifyName: "",
        fxValue: [],
        fqValue: "",
        partId: [],
        mealId: "",
        planId: "",
        planCategoryId: "",
        diagnosisMedical: "",
        doctorNote: "",
      },
      sysSetMealPlanListCopy: [],
      frequencyList: [],
      treatmentMethodsList: [],
      numUnitList: [],
      treatmentParameterList: [],
      doctorPlanText: "",
      isShowStatus: false,
      projectFormRules: {
        partId: [
          {
            required: true,
            message: "部位不能为空",
            trigger: "blur",
          },
        ],
      },
      diagnosisRadio: 0,
      diagnosisRadioVisible: false,
      diagnosisRadioQueryParams: {
        pageNum: 1,
        pageSize: 10,
        visitNum: "",
      },
      diagnosisRadioForm: {
        reviewTime: "",
        visitNum: "",
      },
      diagnosisRadioData: [],
      diagnosisNextItem: "",
      warmReminderVisible: false,
      returnStatus: "0",
      // 折叠面板
      activeName: "",
      //专属医生列表
      doctorList: [],
      userName: this.$store.state.user.name,
      nickName: this.$store.state.user.nickName,
      historyVisible: false,
      historyactiveName: 1,
      // 温馨提示记录
      warmReminderRecordParamsTotal: 0,
      // 检测指标
      Listtotal: 0,
      appointReservaDialogVisible: false,
      latestAppointmentItem: {},
    };
  },

  computed: {
    totalExpenses: function () {
      let all = 0;
      this.sysSetMealPlanListCopy.forEach((item) => {
        if (item.num * item.pointsNum * item.price < item.discountPrice) {
          // setTimeout(() => {
          //   this.$message.warning(
          //     `${item.packageContent}结算价大于总价，请检查`
          //   );
          // }, 10);
        }
        all += Number(item.discountPrice);
      });
      return all.toFixed(2);
    },
    treatmentExpenses: function () {
      let all = 0;
      this.sysSetMealPlanListCopy.forEach((item) => {
        if (item.packageNum === 2) {
          all += Number(item.discountPrice);
        }
      });
      console.log(all);
      return all.toFixed(2);
    },
  },
  mounted() {
    console.log('baseInfo---',this.baseInfo)
    this.queryParams.visitNum = this.baseInfo.visitNum;
    this.queryParams.patientName = this.baseInfo.patientName;
    this.queryParams.sex = this.baseInfo.sex;
    this.queryParams.status = this.baseInfo.status;
    this.queryParams.deptName = this.baseInfo.deptName

    //获取已提醒记录角标
    this.getWarmReminderRecordcount();
    //获取检测指标
    this.getlistDetectionVisit();
    this.getDoctorList();
    this.getClassifyList();
    this.getMealList();
    this.getReviewListTime();
    this.getlatestAppointment();
    this.getPatientList();
    if (this.baseInfo.updateStatus) {
      this.getDoctorEditInfo();
      // this.getReviewListTime()
    }
    if (this.baseInfo.referenceStatus) {
      this.queryParams.doctor = this.baseInfo.doctor;

      this.getReferenceInfo();
    }
    let that = this;
    setTimeout(function () {
      that.dict.type.sys_dosage_frequency.forEach((item) => {
        that.frequencyList.push({ label: item.label, value: item.label });
      });
      that.dict.type.sys_plan_usage.forEach((item) => {
        that.treatmentMethodsList.push({
          label: item.label,
          value: item.label,
        });
      });
      that.dict.type.sys_dosage_unit.forEach((item) => {
        that.numUnitList.push({ label: item.label, value: item.label });
      });
      that.dict.type.sys_treatment_parameter.forEach((item) => {
        that.treatmentParameterList.push({
          label: item.label,
          value: item.label,
        });
      });
    }, 1000);
  },
  methods: {
    addNext() {
      this.appointReservaDialogVisible = true;
    },
    closeAppointReserva() {
      //关闭弹窗
      this.appointReservaDialogVisible = false;
      this.getlatestAppointment();
    },
    closeQrCodeDialog() {
      this.qrCodeOpen = false;
      this.urlText = "";
    },
    //获取已提醒记录角标
    getWarmReminderRecordcount() {
      let warmReminderRecordParams = {
        pageNum: 1,
        pageSize: 10,
        visitNum: "",
      };
      warmReminderRecordParams.visitNum = this.baseInfo.visitNum;
      getTipsList(warmReminderRecordParams).then((response) => {
        if (response.code == 200) {
          this.warmReminderRecordParamsTotal = response.total;
        } else {
        }
      });
    },
    //获取指标录入列表
    getlistDetectionVisit() {
      let detectionIndexForm = {
        pageNum: 1,
        pageSize: 10,
        visitNum: "",
        patientId: "",
      };
      detectionIndexForm.visitNum = this.baseInfo.visitNum;
      listDetectionVisit(detectionIndexForm).then((response) => {
        if (response.rows.length > 0) {
          this.Listtotal = response.total;
        } else {
          this.Listtotal = 0;
        }
      });
    },
    addPlan(visitNum) {
      this.sysSetMealPlanListCopy = [];
      this.getDoctorEditInfo(1, visitNum);
      this.historyVisible = false;
    },
    gethospital(str) {
      if (str) {
        return str;
      } else {
        return "";
      }
    },
    //获取诊断状态字典值对应的label
    getDiagnosisStatusLabel(status) {
      let label = "";
      this.dict.type.sys_diagnosis_status.forEach((item) => {
        if (item.value == status) {
          label = item.label;
        }
      });
      return label;
    },
    onlyWriteNum(e) {
      e.returnValue = ["e", "E", "-", "+", "."].includes(e.key)
        ? false
        : e.returnValue;
      return e;
    },
    numInput(row) {
      this.sysSetMealPlanListCopy.forEach((item, index) => {
        if (row.packageContent == item.packageContent) {
          item.discountPrice = item.num * item.pointsNum * item.price;
        }
      });
    },
    pointsNumInput(row) {
      this.sysSetMealPlanListCopy.forEach((item, index) => {
        if (row.packageContent == item.packageContent) {
          item.discountPrice = item.num * item.pointsNum * item.price;
        }
      });
    },
    priceInput(row) {
      this.sysSetMealPlanListCopy.forEach((item, index) => {
        if (row.packageContent == item.packageContent) {
          item.discountPrice = item.num * item.pointsNum * item.price;
        }
      });
    },
    submitDiagnosisRadioForm() {
      this.diagnosisRadioForm.visitNum = this.baseInfo.visitNum;
      if (this.diagnosisRadioForm.reviewTime) {
        addReview(this.diagnosisRadioForm).then((response) => {
          // this.beforeCloseDiagnosisReview()
          this.getReviewList();
        });
      } else {
        this.$message.warning("请添加复诊提醒日期");
      }
    },
    beforeCloseDiagnosisReview() {
      this.diagnosisRadioVisible = false;
      this.getReviewListTime();
    },
    // 获取顾客登记列表
    showBaseInfoData() {
      //查看记录
      if (this.baseInfoData.length > 1) {
        this.historyVisible = true;
      }
    },
    getPatientList() {
      const patientId = this.baseInfo.patientId;
      const queryParams = { pageNum: 1, pageSize: 9999, patientId: patientId };
      getList(queryParams).then((response) => {
        this.baseInfoData = response.rows;
        this.baseInfoData.forEach((item) => {
          if (item.consultationDiagnosis.includes(";")) {
            let Mobject = "";
            item.consultationDiagnosis.split(";").forEach((it) => {
              Mobject += it + "<br>";
            });
            item.consultationDiagnosisValue = Mobject;
          } else {
            item.consultationDiagnosisValue = item.consultationDiagnosis;
          }
          if (item.doctorDiagnosis.includes(";")) {
            let MobjectDoctor = "";
            item.doctorDiagnosis.split(";").forEach((it) => {
              MobjectDoctor += it + "<br>";
            });
            item.doctorDiagnosisValue = MobjectDoctor;
          } else {
            item.doctorDiagnosisValue = item.doctorDiagnosis;
          }
          if (item.doctorPlan != null) {
            if (item.doctorPlan.includes(";")) {
              let MobjectText = "";
              item.doctorPlan.split(";").forEach((it) => {
                MobjectText += it + "<br>";
              });
              item.doctorPlanValue = MobjectText;
            } else {
              item.doctorPlanValue = item.doctorPlan;
            }
          }
        });
        if (this.baseInfoData.length > 1) {
          this.diagnosisRadio = 1;
          this.returnStatus = this.diagnosisRadio.toString();
          this.changeDiagnosisRadio();
        } else {
          this.diagnosisRadio = 0;
        }
      });
    },
    //初诊还是复诊
    changeDiagnosisRadio() {
      console.log("changeDiagnosisRadio", this.diagnosisRadio);
      if (this.diagnosisRadio == -1) {
        this.$message.warning("请选择本次就诊类型！");
        return false;
      }
      this.returnStatus = this.diagnosisRadio.toString();
      if (this.diagnosisRadio == 1) {
        uploadReview(this.baseInfo.visitNum).then((response) => {
          if (response.code == 200) {
            this.$message.success("选择复诊成功!");
          }
        });
      } else {
        this.$message.success("选择初诊成功!");
      }
    },
    openDiagnosisReview() {
      this.diagnosisRadioVisible = true;
      this.getReviewList();
    },
    openInviteQrcode() {
      // this.urlText =
      //   window.location.origin +
      //   "/share/" +
      //   this.$store.state.user.token +
      //   "/" +
      //   this.baseInfo.patientId +
      //   "/" +
      //   this.baseInfo.visitNum;
      this.urlText1 =
        "http://www.aikeji.top:10001/subPackages/mine/customer/infomation?patientId=" +
        this.baseInfo.patientId +
        "&token=" +
        this.$store.state.user.token;
      this.qrCodeOpen = true;
      this.bindQRCode();
    },
    bindQRCode() {
      this.$nextTick(() => {
        // new QRCode(this.$refs.qrCodeDiv, {
        //   text: this.urlText, //url地址  文本等需要转换为二维码的内容
        //   width: 220,
        //   height: 220,
        //   colorDark: "#00857e", //二维码颜色
        //   colorLight: "#ffffff", //二维码背景色
        //   correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
        // });
        new QRCode(this.$refs.qrCodeDiv1, {
          text: this.urlText1, //url地址  文本等需要转换为二维码的内容
          width: 220,
          height: 220,
          colorDark: "#00857e", //二维码颜色
          colorLight: "#ffffff", //二维码背景色
          correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
        });
      });
    },
    getlatestAppointment() {
      latestAppointment({
        patientId: this.baseInfo.patientId,
      }).then((response) => {
        if (response.code == 200) {
          this.latestAppointmentItem = response.data;
        }
      });
    },
    getReviewListTime() {
      getReview({
        pageNum: 1,
        pageSize: 9999,
        visitNum: this.baseInfo.visitNum,
      }).then((response) => {
        // console.log('addReview', response)
        if (response.code == 200) {
          this.diagnosisRadioData = response.rows;
          this.total = response.total;
          if (this.diagnosisRadioData.length > 0) {
            this.diagnosisNextItem = this.diagnosisRadioData
              .reverse()
              .find((item) => {
                return item.reviewStatus == "0";
              });
          } else {
            this.diagnosisNextItem = "";
          }
        } else {
          this.diagnosisRadioData = [];
        }
      });
    },
    getReviewList() {
      this.loading = true;
      this.diagnosisRadioQueryParams.visitNum = this.baseInfo.visitNum;
      getReview(this.diagnosisRadioQueryParams).then((response) => {
        // console.log('addReview', response)
        if (response.code == 200) {
          this.diagnosisRadioData = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.diagnosisRadioData = [];
          this.loading = false;
        }
      });
    },
    deleteReviewItem(row) {
      // this.loading=true
      deleteReview(row.id).then((response) => {
        if ((response.code = 200)) {
          this.getReviewList();
        }
      });
    },
    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (
        (this.diagnosisRadioQueryParams.pageNum - 1) *
          this.diagnosisRadioQueryParams.pageSize +
        index +
        1
      );
    },
    //查询咨询医生
    getDoctorList() {
      console.log('getDoctorList--this.baseInfo',this.baseInfo)
      getListUser({ funcRole: "2",hospitalId:this.baseInfo.hospitalId,deptId:this.baseInfo.deptId   }).then((response) => {
        if (response.code == 200) {
          this.doctorList = response.data;
          if (this.doctorList.length > 0) {
            let a = this.doctorList.some((item) => {
              return item.nickName == this.nickName;
            });
            if (this.baseInfo.doctor) {
              this.queryParams.doctor = this.baseInfo.doctor;
            } else {
              if (a) {
                this.queryParams.doctor = this.nickName;
              }
            }
          }
        }
      });
    },
    // 录入指标 saveDetection
    handleAdd() {
      //新增检测指标
      this.baseAdd = {};
      this.baseAdd.isDetail = true;
      this.baseAdd.visitNum = this.queryParams.visitNum;
      this.baseAdd.patientName = this.queryParams.patientName;
      this.baseAdd.patientId = this.baseInfo.patientId;
      this.baseAdd.deptId = this.baseInfo.deptId
      console.log(this.baseAdd);
      this.planTitle = "检测指标";
      this.centerDialogVisible = true;
    },
    closeCenterDialogVisible() {
      this.centerDialogVisible = false;
      this.getlistDetectionVisit();
    },
    /** 医嘱参数值悬浮时提交值 */
    submitOptions(index) {
      let text = "";
      this.sysSetMealPlanListCopy[index].parametersList.forEach(
        (item, index) => {
          text += item.label + "(" + item.value + ");";
        }
      );
      this.sysSetMealPlanListCopy[index].parameters = text;
      this.isShowStatus = true;
      setTimeout(() => {
        this.isShowStatus = false;
      }, 500);
      this.$message.success("医嘱参数提交成功");
    },
    /** 医嘱参数值悬浮时删除值 */
    delOptions(row, index) {
      this.sysSetMealPlanListCopy[index].parametersList =
        this.sysSetMealPlanListCopy[index].parametersList.filter((item) => {
          return item.label != row.label;
        });
    },
    /** 删除方案信息 */
    deletePlanItem(row) {
      this.arr = JSON.stringify(this.sysSetMealPlanListCopy);
      this.sysSetMealPlanListCopy = JSON.parse(this.arr).filter((item) => {
        return row.packageContent != item.packageContent;
      });
    },
    /** 获取方案信息 */
    getDoctorEditInfo(type, Num) {
      //type==1  引用方案   其它为修改方案
      let visitNum = this.queryParams.visitNum;
      if (type == 1) {
        visitNum = Num;
      }
      doctorEdit(visitNum).then((res) => {
        console.log("getDoctorEditInfo---", res);
        if (type == 1) {
          //&&this.baseInfo.updateStatus
          this.baseInfo.id = this.baseInfo.id;
        } else {
          this.baseInfo.id = res.Info[0].id;
        }
        this.diagnosisList = JSON.parse(res.Info[0].doctorDiagnosis);
        this.projectForm.doctorNote = res.Info[0].doctorNote;
        this.projectForm.diagnosisMedical = res.Info[0].diagnosisMedical;

        this.diagnosisList = JSON.parse(res.Info[0].doctorDiagnosis);
        this.projectForm.doctorNote = res.Info[0].doctorNote;
        this.projectForm.diagnosisMedical = res.Info[0].diagnosisMedical;
        // this.totalExpenses = res.Info[0].totalExpenses
        // this.treatmentExpenses = res.Info[0].treatmentExpenses
        res.plan.rows.forEach((item) => {
          this.queryParams.doctor = item.nickName;
          this.sysSetMealPlanListCopy.push({
            pointsNum: item.pointsNum ? item.pointsNum : 1,
            planCategoryId: item.planCategoryId,
            treatmentType: item.planCategoryId == "2" ? "治疗类" : "",
            searchValue: item.searchValue,
            createBy: item.createBy,
            createTime: item.createTime,
            updateBy: item.updateBy,
            updateTime: item.updateTime,
            remark: item.remark,
            params: {},
            id: item.id,
            visitNum: this.queryParams.visitNum,
            type: item.type,
            category: item.category,
            treatmentModalities: item.treatmentModalities,
            packageName: item.packageName,
            packageNum: item.packageNum,
            packageContent: item.packageContent,
            frequency: item.frequency,
            dosage: item.dosage,
            num: item.num,
            numUnit: item.numUnit,
            price: item.price,
            priceUnit: item.priceUnit,
            discount: item.discount,
            totalPrice: item.totalPrice,
            diagnosisResult: item.diagnosisResult,
            diagnosisMedical: item.diagnosisMedical,
            diagnosisNote: item.diagnosisNote,
            expenses: item.expenses,
            status: item.status,
            instruments: item.instruments,
            instrumentsIds: item.instrumentsIds,
            parameters: item.parameters
              ? this.getParametersValue(item.parameters)
              : null,
            parametersList: item.parameters
              ? JSON.parse(item.parameters)
              : null,
            isApplication: item.isApplication,
            pickingLocation: item.pickingLocation,
            sPlanId: item.sPlanId,
            discountPrice: item.discountPrice
              ? item.discountPrice
              : Number(item.num * item.pointsNum * item.price),
          });
        });
      });
    },
    getParametersValue(row) {
      // console.log(row)
      let text = "";
      JSON.parse(row).forEach((item, index) => {
        text += item.label + "(" + item.value + ");";
      });
      return text;
    },
    /** 数组对象去重 */
    uniqueFunc(arr, uniId) {
      const res = new Map();
      return arr.filter(
        (item) => !res.has(item[uniId]) && res.set(item[uniId], 1)
      );
    },
    /** 方案数据提取咨询方案文本 */
    getDoctorPlanText() {
      let packageArr = this.sysSetMealPlanListCopy.filter((item) => {
        return item.category == "1";
      });
      //根据套餐名称去重
      let distinctPackageArr = this.uniqueFunc(packageArr, "packageName");
      let singleArr = this.sysSetMealPlanListCopy.filter((item) => {
        return item.category == "2";
      });
      distinctPackageArr.forEach((item) => {
        let mArr = this.sysSetMealPlanListCopy.filter((mIt) => {
          return item.packageName == mIt.packageName;
        });
        this.doctorPlanText += item.packageName + "{";
        mArr.forEach((mItem, index) => {
          if (index == mArr.length - 1) {
            this.doctorPlanText +=
              mItem.packageContent + "*" + mItem.num + "};";
          } else {
            this.doctorPlanText +=
              mItem.packageContent + "*" + mItem.num + "、";
          }
        });
      });
      singleArr.forEach((item) => {
        this.doctorPlanText += item.packageContent + "*" + item.num + ";";
      });
    },
    /** 修改方案所有信息 */
    updateAllPlan() {
      if (!this.queryParams.doctor) {
        this.$message.warning("请选择诊断医生!");
        return;
      }
      let a = this.doctorList.find((item) => {
        return item.nickName == this.queryParams.doctor;
      });
      this.getDoctorPlanText();
      let Mdata = {
        id: this.baseInfo.id,
        visitNum: this.baseInfo.visitNum,
        doctorDiagnosis: JSON.stringify(this.diagnosisList),
        doctorNote: this.projectForm.doctorNote,
        diagnosisMedical: this.projectForm.diagnosisMedical,
        sysVisitPlan: this.sysSetMealPlanListCopy.map((item) => ({
          ...item,
          parameters: item.parametersList
            ? JSON.stringify(item.parametersList)
            : null,
          totalPrice: Number(item.num * item.price),
          returnStatus: this.returnStatus,
        })),
        totalExpenses: this.totalExpenses,
        treatmentExpenses: this.treatmentExpenses,
        doctorPlan: this.doctorPlanText,
        nickName: this.queryParams.doctor,
        doctorUserName: a.userName,
      };

      if (this.diagnosisList.length == 0) {
        this.$message.warning("请添加诊断!");
      } else {
        if (Mdata.sysVisitPlan.length > 0) {
          const isExit = !!Mdata.sysVisitPlan.find((item) => {
            return item.num == null || item.num == 0;
          });
          if (isExit) {
            this.$message.warning("存在数量为0的单项，请仔细核对");
          } else {
            updateDoctorPlan(Mdata).then((res) => {
              if (res.code === 200) {
                this.$message.success("修改成功");
                this.$emit("closeCenterDialogVisible");
              }
            });
          }
        } else {
          this.$confirm("该顾客没有方案?请确认", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then((content) => {
              updateDoctorPlan(Mdata).then((res) => {
                if (res.code === 200) {
                  this.$message.success("修改成功");
                  this.$emit("closeCenterDialogVisible");
                }
              });
            })
            .catch((error) => {
              // console.log('error', error)
            });
        }
      }
    },
    /** 保存方案所有信息 */
    saveAllPlan() {
      if (!this.queryParams.doctor) {
        this.$message.warning("请选择诊断医生!");
        return;
      }
      let a = this.doctorList.find((item) => {
        return item.nickName == this.queryParams.doctor;
      });
      this.getDoctorPlanText();
      let Mdata = {
        visitNum: this.baseInfo.visitNum,
        doctorDiagnosis: JSON.stringify(this.diagnosisList),
        doctorNote: this.projectForm.doctorNote,
        diagnosisMedical: this.projectForm.diagnosisMedical,
        sysVisitPlan: this.sysSetMealPlanListCopy.map((item) => ({
          ...item,
          parameters: item.parametersList
            ? JSON.stringify(item.parametersList)
            : null,
          totalPrice: Number(item.num * item.pointsNum * item.price),
        })),
        status: this.returnStatus,
        totalExpenses: this.totalExpenses,
        treatmentExpenses: this.treatmentExpenses,
        doctorPlan: this.doctorPlanText,
        nickName: this.queryParams.doctor,
        doctorUserName: a.userName,
      };

      if (this.diagnosisList.length == 0) {
        this.$message.warning("请添加诊断!");
      } else {
        if (Mdata.sysVisitPlan.length > 0) {
          const isExit = !!Mdata.sysVisitPlan.find((item) => {
            return item.num == null || item.num == 0;
          });
          if (isExit) {
            this.$message.warning("存在数量为空的单项，请仔细核对");
          } else {
            addDoctorPlan(Mdata).then((res) => {
              if (res.code === 200) {
                this.$message.success("新增成功");
                this.$emit("closeCenterDialogVisible");
              }
            });
          }
        } else {
          this.$confirm("该顾客没有方案?请确认", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then((content) => {
              addDoctorPlan(Mdata).then((res) => {
                if (res.code === 200) {
                  this.$message.success("新增成功");
                  this.$emit("closeCenterDialogVisible");
                }
              });
            })
            .catch((error) => {
              // console.log('error', error)
            });
        }
      }

      // if (Mdata.sysVisitPlan.length > 0) {
      //   addDoctorPlan(Mdata).then((res) => {
      //     if (res.recognizeCode === 200) {
      //       this.$message.success('新增成功')
      //       this.$emit('closeCenterDialogVisible')
      //     }
      //   })
      // } else {
      //   this.$message.warning('请添加套餐或单项!')
      // }
    },
    /** 获取咨询方案信息 */
    getReferenceInfo() {
      getDoctorReference(this.queryParams.visitNum).then((res) => {
        console.log("getDoctorReference", res);
        this.baseInfo.id = res.Info[0].id;
        this.diagnosisList = JSON.parse(res.Info[0].consultationDiagnosis);
        this.projectForm.doctorNote = res.Info[0].consultationNote;
        this.projectForm.diagnosisMedical = res.Info[0].diagnosisMedical;

        res.plan.rows.forEach((item) => {
          this.sysSetMealPlanListCopy.push({
            pointsNum: item.pointsNum ? item.pointsNum : 1,
            planCategoryId: item.planCategoryId,
            treatmentType: item.planCategoryId == "2" ? "治疗类" : "",
            searchValue: item.searchValue,
            createBy: item.createBy,
            createTime: item.createTime,
            updateBy: item.updateBy,
            updateTime: item.updateTime,
            remark: item.remark,
            params: {},
            id: item.id,
            visitNum: item.visitNum,
            type: item.type,
            category: item.category,
            treatmentModalities: item.treatmentModalities,
            packageName: item.packageName,
            packageNum: item.packageNum,
            packageContent: item.packageContent,
            frequency: item.frequency,
            dosage: item.dosage,
            num: item.num,
            numUnit: item.numUnit,
            price: item.price,
            priceUnit: item.priceUnit,
            discount: item.discount,
            totalPrice: item.totalPrice,
            diagnosisResult: item.diagnosisResult,
            diagnosisMedical: item.diagnosisMedical,
            diagnosisNote: item.diagnosisNote,
            expenses: item.expenses,
            status: item.status,
            instruments: item.instruments,
            instrumentsIds: item.instrumentsIds,
            parameters: item.parameters
              ? this.getParametersValue(item.parameters)
              : null,
            parametersList: item.parameters
              ? JSON.parse(item.parameters)
              : null,
            isApplication: item.isApplication,
            pickingLocation: item.pickingLocation,
            sPlanId: item.sPlanId,
            discountPrice: item.discountPrice
              ? item.discountPrice
              : Number(item.num * item.pointsNum * item.price),
          });
        });
      });
    },
    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },

    /** 获取套餐列表 */
    getMealList() {
      listMealDept({
        pageNum: 1,
        pageSize: 9999,
        status: 0,
        deptId:this.baseInfo.deptId,
      }).then((response) => {
        this.mealList = response.rows;
      });
    },
    changeList() {
      this.singlePlanList = [];
      this.projectForm.planId = "";
      this.getSinglePlanList();
    },
    /** 获取单项列表 */
    getSinglePlanList() {
      listPlanDept({
        pageNum: 1,
        pageSize: 9999,
        status: 0,
        planCategoryId: this.projectForm.planCategoryId,
        deptId:this.baseInfo.deptId
      }).then((response) => {
        this.singlePlanList = response.rows;
      });
    },
    /** 查询专病列表 */
    getClassifyList() {
      listClassify({
        pageNum: 1,
        pageSize: 9999,
        status: 0,
      }).then((response) => {
        this.classifyList = response.rows;
      });
    },
    /** 专病名称选择后筛选出分型和分期 */
    getFxAndFq(row) {
      console.log(row);
      this.activeName = "1";
      this.classifyList.forEach((item) => {
        if (item.diseaseClassifyName === row) {
          this.projectForm.diseaseId = item.diseaseClassifyId;
          this.Fx = JSON.parse(item.diseaseType);
          this.Fq = JSON.parse(item.diseaseSerialization);
        }
      });
    },
    openCollapse() {
      this.activeName = "1";
    },
    /** 添加套餐 */
    addPackage() {
      const that = this;
      if (!this.projectForm.mealId) {
        this.$message.warning("请选择套餐");
      } else {
        getMeal(this.projectForm.mealId).then((response) => {
          console.log("addPackage---", response);
          let warnText = "";
          response.data.sysSetMealPlanList.forEach((item) => {
            let isExist = this.sysSetMealPlanListCopy.filter((it) => {
              return item.medicalEquipment == it.packageContent;
            });
            if (isExist.length > 0) {
              warnText = warnText + isExist[0].packageContent + ",";
            } else {
              that.sysSetMealPlanListCopy.push({
                pointsNum: 1,
                planCategoryId: item.planCategoryId,
                treatmentType: item.planCategoryId == "2" ? "治疗类" : "",
                packageContent: item.medicalEquipment,
                searchValue: item.searchValue,
                createBy: item.createBy,
                createTime: item.createTime,
                updateBy: item.updateBy,
                updateTime: item.updateTime,
                remark: item.remark,
                params: {},
                id: 0,
                sPlanId: item.planId,
                visitNum: item.visitNum,
                type: "2",
                category: "1",
                treatmentModalities: that.matchDict(
                  "sys_plan_usage",
                  item.usageId
                ),
                packageName: response.data.setMealName,
                packageNum: Number(item.planCategoryId),
                frequency: that.matchDict(
                  "sys_dosage_frequency",
                  item.frequencyId
                ),
                dosage: item.dosage,
                num: item.num ? item.num : 1,
                numUnit: that.matchDict("sys_dosage_unit", item.dosageUnit),
                price: item.price,
                priceUnit: item.priceUnit,
                discount: item.discount,
                diagnosisResult: item.diagnosisResult,
                diagnosisMedical: item.diagnosisMedical,
                diagnosisNote: item.diagnosisNote,
                expenses: item.expenses,
                status: item.status,
                instruments: item.instruments,
                instrumentsIds: item.instrumentsIds,
                parameters: item.parameters
                  ? this.getParametersValue(item.parameters)
                  : null,
                parametersList: item.parameters
                  ? JSON.parse(item.parameters)
                  : null,
                isApplication: item.isApplication,
                pickingLocation: item.pickingLocation,
                totalPrice: Number(item.num * item.price), //添加单项时不用乘item.pointsNum   添加时item.pointsNum默认为1
                discountPrice: item.discountPrice
                  ? item.discountPrice
                  : Number(item.num * item.price), //添加单项时不用乘item.pointsNum   添加时item.pointsNum默认为1
              });
            }
          });
          if (warnText == "") {
            // this.$message.success('添加成功')
          } else {
            // this.$message.warning('添加成功，' + warnText + '已存在，已自动过滤此单项')
            this.$message.warning("该套餐已存在，已自动过滤此单项");
          }
        });
      }
    },

    addSingle() {
      if (!this.projectForm.planId) {
        this.$message.warning("请选择单项");
      } else {
        const isExist = this.sysSetMealPlanListCopy.filter((item) => {
          return item.sPlanId == this.projectForm.planId;
        });
        if (isExist.length > 0) {
          this.$message.warning("已存在，请勿重复添加此单项");
        } else {
          console.log("addSingle", this.sysSetMealPlanListCopy);
          this.singlePlanList.forEach((item) => {
            if (this.projectForm.planId === item.planId) {
              this.sysSetMealPlanListCopy.push({
                pointsNum: 1,
                planCategoryId: item.planCategoryId,
                treatmentType: item.planCategoryId == "2" ? "治疗类" : "",
                packageContent: item.medicalEquipment,
                searchValue: item.searchValue,
                createBy: item.createBy,
                createTime: item.createTime,
                updateBy: item.updateBy,
                updateTime: item.updateTime,
                remark: item.remark,
                params: {},
                id: 0,
                sPlanId: item.planId,
                visitNum: item.visitNum,
                type: "2",
                category: "2",
                treatmentModalities: this.matchDict(
                  "sys_plan_usage",
                  item.usageId
                ),
                packageName: "",
                packageNum: Number(item.planCategoryId),
                frequency: this.matchDict(
                  "sys_dosage_frequency",
                  item.frequencyId
                ),
                dosage: item.dosage,
                num: item.num ? item.num : 1,
                numUnit: this.matchDict("sys_dosage_unit", item.dosageUnit),
                price: item.price,
                priceUnit: item.priceUnit,
                discount: item.discount,
                diagnosisResult: item.diagnosisResult,
                diagnosisMedical: item.diagnosisMedical,
                diagnosisNote: item.diagnosisNote,
                expenses: item.expenses,
                status: item.status,
                instruments: item.instruments,
                instrumentsIds: item.instrumentsIds,
                parameters: item.parameters
                  ? this.getParametersValue(item.parameters)
                  : null,
                parametersList: item.parameters
                  ? JSON.parse(item.parameters)
                  : null,
                isApplication: item.isApplication,
                pickingLocation: item.pickingLocation,
                totalPrice: Number(item.num * item.price), //添加单项时不用乘item.pointsNum   添加时item.pointsNum默认为1
                discountPrice: item.discountPrice
                  ? item.discountPrice
                  : Number(item.num * item.price), //添加单项时不用乘item.pointsNum   添加时item.pointsNum默认为1
              });
            }
          });
          this.projectForm.planId = "";
        }
      }
    },
    updateItemDiagnosis(item) {
      this.currentDiagnosis = item;
      this.btnUpdateStatus = true;
      let arr = item.diagnosis.split("、");
      this.projectForm.diseaseClassifyName = arr[0];
      this.getFxAndFq(this.projectForm.diseaseClassifyName);
      // this.projectForm.fxValue = arr[1]
      this.projectForm.fxValue = [];
      arr[1].split(",").forEach((item) => {
        this.projectForm.fxValue.push(item);
      });
      this.projectForm.fqValue = arr[2];
      this.projectForm.partId = [];
      arr[3].split(",").forEach((item) => {
        this.projectForm.partId.push(item);
      });
    },
    delDiagnosis(row) {
      this.diagnosisList = this.diagnosisList.filter((item) => {
        return row.id != item.id;
      });
      if (this.diagnosisList.length > 1) {
        this.diagnosisList.forEach((item, index) => {
          item.id = index;
        });
      }
      // this.projectForm.fxValue = ''
      this.projectForm.fxValue = [];
      this.projectForm.fqValue = "";
      this.projectForm.partId = [];
    },
    /**添加诊断按钮操作 */
    addDiagnosis() {
      this.$refs["projectForm"].validate((valid) => {
        if (valid) {
          if (this.projectForm.diseaseClassifyName != "") {
            this.activeName = "";
            let arrA = this.dict.type.sys_face_part;
            let arrB = this.projectForm.partId;
            let arrC = arrA.filter((item) =>
              arrB.some((citem) => item.label === citem)
            );

            for (const key in arrC) {
              // 删除raw属性
              delete arrC[key].raw;
            }
            if (this.diagnosisList.length === 0) {
              this.diagnosisList.push({
                id: 0,
                partArr: arrC,
                diseaseId: this.projectForm.diseaseId,
                diagnosis:
                  (this.projectForm.diseaseClassifyName
                    ? `${this.projectForm.diseaseClassifyName + "、"}`
                    : "") +
                  (this.projectForm.fxValue.length > 0
                    ? `${this.projectForm.fxValue + "、"}`
                    : "") +
                  (this.projectForm.fqValue
                    ? `${this.projectForm.fqValue + "、"}`
                    : "") +
                  this.projectForm.partId,
              });
            } else {
              this.diagnosisList.push({
                id: this.diagnosisList.length,
                partArr: arrC,
                diseaseId: this.projectForm.diseaseId,
                diagnosis:
                  (this.projectForm.diseaseClassifyName
                    ? `${this.projectForm.diseaseClassifyName + "、"}`
                    : "") +
                  (this.projectForm.fxValue.length > 0
                    ? `${this.projectForm.fxValue + "、"}`
                    : "") +
                  (this.projectForm.fqValue
                    ? `${this.projectForm.fqValue + "、"}`
                    : "") +
                  this.projectForm.partId,
              });
            }
          } else {
            this.$message.warning("没有诊断可加入，请选择要加入的诊断");
          }
          // this.projectForm.fxValue = ''
          this.projectForm.fxValue = [];
          this.projectForm.fqValue = "";
          this.projectForm.partId = [];
        }
      });
    },
    updateDiagnosis() {
      this.btnUpdateStatus = false;
      this.diagnosisList.forEach((item) => {
        if (item.id === this.currentDiagnosis.id) {
          item.diagnosis = `${
            this.projectForm.diseaseClassifyName +
            "、" +
            this.projectForm.fxValue +
            "、" +
            this.projectForm.fqValue +
            "、" +
            this.projectForm.partId
          }`;
        }
      });
      // this.projectForm.fxValue = ''
      this.projectForm.fxValue = [];
      this.projectForm.fqValue = "";
      this.projectForm.partId = [];
    },
    //温馨提示
    warmReminder() {
      this.warmReminderVisible = true;
    },
    closeWarmReminderVisible() {
      this.warmReminderVisible = false;
      this.getWarmReminderRecordcount();
    },
  },
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
.l-h-60 {
  line-height: 60px;
}

.tips1 {
  width: 550px;
  line-height: 40px;
  margin: 0 auto 15px auto;
  background-color: #fefa83;
  border-radius: 50px;
  color: #000;
  font-size: 16px;
  text-align: center;
}

.tips {
  width: 550px;
  line-height: 40px;
  margin: 0 auto 15px auto;
  background-color: #75f9fd;
  border-radius: 50px;
  color: #000;
  font-size: 16px;
  text-align: center;
}

.price {
  background-color: #eee;
  line-height: 30px;
  text-align: center;
  color: #1890ff;
  font-size: 16px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #606266;
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #1890ff !important;
}

::v-deep .el-collapse-item__header {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mt5 {
  margin-top: 5px;
}

.mt15 {
  margin-bottom: 15px;
  margin-right: 15px;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield;
}

.totalItem {
  margin: 0 5px;
}
.qrcode {
  width: 220px;
  margin: 0 auto;
}
.qrcode-box {
  display: flex;
}
</style>
